package com.ranjiaqi.upload;

import java.io.*;
import java.net.Socket;
import java.util.Random;

/**
 * @ClassName SocketRunnable
 * @Description TODO
 * @Author hp
 * @Date 2021/7/4 18:13
 * @Version 1.0
 **/
public class SocketRunnable implements Runnable {
    private Socket socket;

    public SocketRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            File uploadDir = new File("E://upload");
            if(!uploadDir.exists())
                uploadDir.mkdirs();
            String fileName = "ranjiaqi"+System.currentTimeMillis()+new Random().nextInt(9999)+".txt";
            BufferedInputStream bis= new  BufferedInputStream(socket.getInputStream()) ;
            BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(new File(uploadDir,fileName)));
            byte[] bytes = new byte[1024 * 5];
            int len = 0 ;
            while ((len = bis.read(bytes))!=-1){
                bw.write(bytes,0,len);
                bw.flush();
            }
            BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
            bos.write("文件下载成功".getBytes());
            bos.close();
            socket.close();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
